from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import *
from django.db.models import QuerySet
from rest_framework.views import APIView
from rest_framework.request import HttpRequest
from django.http import HttpResponse
from rest_framework.response import Response
from io import BytesIO
import time
import random
import requests
from PIL import Image, ImageDraw, ImageFont
from django.conf import settings


class RegionViewSet(ModelViewSet):
    pagination_class = None
    serializer_class = RegionSerializer
    queryset = Region.objects.all()

    def filter_queryset(self, queryset: QuerySet) -> QuerySet:
        if self.request.method == 'GET':
            return queryset.filter(user_id=self.request.user.id,parent_region=None).all()
        else:
            return queryset.filter(user_id=self.request.user.id).all()

class UploadFile(APIView):
    def post(self, request: HttpRequest, *args, **kwargs):
        file = request.FILES.get('file')

        if not file:
            return Response({
                'code': 500,
                'msg': '文件不能为空'
            }, 400)
        path = f'./static/images/{int(time.time())}{file.name}'
        url = f'http://106.54.240.219:8000/static/images/{int(time.time())}{file.name}'
        with open(path, 'wb') as f:

            f.write(file.read())

        return Response({
            "name": file.name,
            "status": "done",
            "url": url,
            "thumbUrl": url
        })


class GenNumberImageView(APIView):

    authentication_classes = []

    def get(self, reqeust, *args, **kwargs):
        random_str = self.gen_random_string()
        reqeust.session['code'] = random_str

        image = Image.new("RGB", (500, 200), color=(random.randrange(
            0, 266), random.randrange(0, 266), random.randrange(0, 266)))

        draw = ImageDraw.Draw(image)
        defaultfont = ImageFont.truetype(settings.CODE_FONT_PATH, 120,)

        font_row_area = 200 // 2
        font_column_area = 500 // len(random_str)
        index = 0
        for i in random_str:
            draw.text(
                (
                    random.randint(
                        font_column_area * index,
                        font_column_area * index + 30,
                    ),
                    random.randint(
                        font_row_area - 70,
                        font_row_area
                    )
                ),
                text=i,
                fill=self.gen_random_color(),
                font=defaultfont
            )
            index += 1
        for i in range(1000):
            draw.point(
                (
                    random.randrange(0, 501),
                    random.randrange(0, 201),
                ),
                fill=self.gen_random_color(),
            )
            if i > 10:
                continue
            x, y = random.randrange(0, 501), random.randrange(50, 150)
            draw.line(
                (
                    (
                        x, y
                    ),
                    (
                        x+1, y+1
                    )
                ),
                width=random.randrange(100, 501),
                fill=self.gen_random_color(),
            )
        res = BytesIO()
        image.save(res, format='png')
        res.seek(0)
        return HttpResponse(res.getvalue(), content_type="image/png")
        # return StreamingHttpResponse(res)

    def gen_random_string(self, code_length=4):

        strs = list(
            '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZzbcdefghijklmnopqrstuvwxyz'
        )

        range_area = len(strs)

        random.randrange(0, range_area)

        return ''.join((strs[random.randrange(0, range_area)] for i in range(code_length)))

    def gen_random_color(self):
        hex_str = list('0123456789ABCDEF')

        return '#' + ''.join((hex_str[random.randrange(0, len(hex_str))] for i in range(6)))


class WeatherView(APIView):
    authentication_classes = []

    def get(self, request, *args, **kwargs):
        location = request.query_params.get('location')
        if not location:
            return Response({
                'code': 400,
                'msg': '不合法的区域'
            })
        response = requests.get(
            'http://restapi.amap.com/v3/geocode/regeo',
            params={
                'key': 'c3867cfadd54a4c6c9e29cdf13149a0f',
                'location': location
            }
        )
        data = response.json()
        # return Response(data)
        try:
            geocodes = data['regeocode']['addressComponent']
        except Exception as e:
            geocodes = {"adcode": "310115"}
        adcode = geocodes['adcode']
        response = requests.get(
            'http://restapi.amap.com/v3/weather/weatherInfo',
            params={
                'key': 'c3867cfadd54a4c6c9e29cdf13149a0f',
                'city': adcode
            }
        )

        return Response({
            'code': 200,
            'data': response.json()['lives'][0]
        })
